// Task.hpp
#pragma once
#include <iostream>
#include <string>
#include "Init.hpp"

Init init;  // 定义成全局对象，对象定义时，init对象就会被构造，调用构造函数时就会把整个词典加载到dict里

class Task
{
public:
    Task(int sockfd, const std::string &clientip, uint16_t clientport)
        : _sockfd(sockfd), _clientip(clientip), _clientport(clientport)
    {
    }

    // 翻译
    void run()
    {
        char buffer[4096];
        ssize_t n = read(_sockfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "client key# " << buffer << std::endl;

            std::string echo_string = init.translation(buffer);
            int m = write(_sockfd, echo_string.c_str(), echo_string.size());
            if (m < 0)
            {
                lg(Warning, "write error, errno: %d, strerror: %s", errno, strerror(errno));
            }
        }
        else if (n < 0)
        {
            lg(Warning, "read error, sockfd: %d, client ip: %s, client port: %d", _sockfd, _clientip.c_str(), _clientport);
        }
        else // (n == 0)
        {
            lg(Info, "%s:%d quit, server close sockfd: %d", _clientip.c_str(), _clientport, _sockfd);
        }
        close(_sockfd);
    }

    // // 接收到什么就返回什么
    // void run()
    // {
    //     char buffer[4096];
    //     ssize_t n = read(_sockfd, buffer, sizeof(buffer));
    //     if (n > 0)
    //     {
    //         buffer[n] = 0;
    //         std::cout << "client say# " << buffer << std::endl;

    //         std::string echo_string = "tcpserver echo# ";
    //         echo_string += buffer;
    //         int m = write(_sockfd, echo_string.c_str(), echo_string.size());
    //         if (m < 0)
    //         {
    //             lg(Warning, "write error, errno: %d, strerror: %s", errno, strerror(errno));
    //         }
    //     }
    //     else if (n < 0)
    //     {
    //         lg(Warning, "read error, sockfd: %d, client ip: %s, client port: %d", _sockfd, _clientip.c_str(), _clientport);
    //     }
    //     else // (n == 0)
    //     {
    //         lg(Info, "%s:%d quit, server close sockfd: %d", _clientip.c_str(), _clientport, _sockfd);
    //     }
    //     close(_sockfd);
    // }

    // 运算符重载
    void operator()()
    {
        run();
    }
    ~Task()
    {
    }

private:
    int _sockfd;
    std::string _clientip;
    uint16_t _clientport;
};
